<template>
  <el-dialog
    v-model="visible"
    :title="isEditing ? '编辑学生信息' : '创建学生信息'"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="left"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入学生姓名" />
      </el-form-item>

      <el-form-item label="年级" prop="grade">
        <el-select v-model="form.grade" placeholder="请选择年级" style="width: 100%">
          <el-option label="一年级" value="一年级" />
          <el-option label="二年级" value="二年级" />
          <el-option label="三年级" value="三年级" />
          <el-option label="四年级" value="四年级" />
          <el-option label="五年级" value="五年级" />
          <el-option label="六年级" value="六年级" />
          <el-option label="初一" value="初一" />
          <el-option label="初二" value="初二" />
          <el-option label="初三" value="初三" />
          <el-option label="高一" value="高一" />
          <el-option label="高二" value="高二" />
          <el-option label="高三" value="高三" />
        </el-select>
      </el-form-item>

      <el-form-item label="班级" prop="className">
        <el-input v-model="form.className" placeholder="请输入班级，如：1班、2班" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEditing ? '更新' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useStudentStore } from '@/store/student'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  student: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const formRef = ref()
const loading = ref(false)
const studentStore = useStudentStore()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEditing = computed(() => !!props.student)

const form = ref({
  name: '',
  grade: '',
  className: ''
})

const rules = {
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' },
    { min: 1, max: 10, message: '班级长度在 1 到 10 个字符', trigger: 'blur' }
  ]
}

// 监听学生数据变化，填充表单
watch(() => props.student, (student) => {
  if (student) {
    form.value = {
      name: student.name || '',
      grade: student.grade || '',
      className: student.className || ''
    }
  } else {
    form.value = {
      name: '',
      grade: '',
      className: ''
    }
  }
}, { immediate: true })

// 监听对话框开关，重置表单
watch(visible, (newVisible) => {
  if (newVisible) {
    formRef.value?.clearValidate()
  }
})

const handleClose = () => {
  visible.value = false
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    if (isEditing.value) {
      await studentStore.updateStudentInfo({
        id: props.student.id,
        ...form.value
      })
      ElMessage.success('学生信息更新成功')
    } else {
      await studentStore.createStudent(form.value)
      ElMessage.success('学生信息创建成功')
    }

    emit('success')
    handleClose()
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error(isEditing.value ? '更新失败，请重试' : '创建失败，请重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-select) {
  width: 100%;
}
</style>